#include "server.h"

#include <arpa/inet.h>
#include <memory>

#include "util.h"
#include "global_env.h"
#include <string.h>
#include <functional>

Server::Server(EventLoop* loop):
    loop_(loop),
    acceptor_(new Acceptor(loop)),
    thdPool_(new EventLoopThreadPool(loop, THREADPOOL_THREAD_NUM))
{
    acceptor_->SetCB(
        std::bind(&Server::HandleConnection, this, std::placeholders::_1)
    );
}

Server::~Server(){}

void Server::Start()
{
    // thdPool_->Start();
    loop_->RunInLoop(std::bind(&Acceptor::Listen, acceptor_.get()));
}

// 建立连接并且分配到新的eventloop中
void Server::HandleConnection(int acceptFd)
{
    EventLoop* loop = thdPool_->getNextLoop();
    
    RequestDataPtr req = std::make_shared<RequestData>(loop, acceptFd);
    // req 不需要设置各种回调，它自身实现了
    requestDataPtrs[acceptFd] = req;

    loop->RunInLoop(std::bind(&RequestData::ConnectionEstablished, req));
}
